﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestLogMonitor.Common;

namespace TestLogMonitor.Helper
{
    public class FileHelper
    {
        /// <summary>
        /// 移动文件到目录路径下
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <returns>boole</returns>
        public static bool MoveFile(string sourceFileName,string destFileName,bool isBackup=true,string backupPath="")
        {
            try
            {
                string destDirectoryName= Path.GetDirectoryName(destFileName);
                if (!Directory.Exists(destDirectoryName))
                    Directory.CreateDirectory(destDirectoryName);
                File.Copy(sourceFileName, destFileName, true);
                //备份记录
                if (isBackup)
                {
                    //文件的创建日期
                    string fileCreateDate= BusinessProcess.ConvertDatetime(Path.GetFileNameWithoutExtension(sourceFileName).Split('_')[1]).Date.ToString("yyyy-MM-dd");//文件的日期部分 File.GetCreationTime(sourceFileName).ToString("yyyy-MM-dd");
                    //备份路径下创建指定的日期格式子文件夹
                    string backupDirectoryName = Path.Combine(backupPath + "\\" + GlobalInfo.Product, fileCreateDate);
                    if (!Directory.Exists(backupDirectoryName))
                        Directory.CreateDirectory(backupDirectoryName);
                    string backupFileName = Path.Combine(backupDirectoryName, Path.GetFileName(sourceFileName));
                    File.Copy(sourceFileName, backupFileName,true);
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return false;
            }
            File.Delete(sourceFileName);
            return true;
        }
        //判断文件是否正在使用
        public static bool IsFileUsed(string filePath)
        {
            try
            {
                //改变文件的只读属性
                FileHelper.ChangeReadOnlyAttribute(filePath);
                using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    return false;// 文件没有被使用，可以进行操作
                }
            }
            catch (IOException)
            {
                return true; //文件正在使用
            }
        }
        //改变文件的只读属性
        public static void ChangeReadOnlyAttribute(string filePath)
        {
            // 获取当前文件的属性
            var attributes = File.GetAttributes(filePath);

            // 如果只读属性被设置，则清除它
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                // 清除只读属性
                File.SetAttributes(filePath, attributes & ~FileAttributes.ReadOnly);
            }
        }
    }
}
